<template>
  <div class="app-container">
    <!-- 添加用户按钮 -->
    <el-button type="primary" @click="handleAddUser">创建新的用户</el-button>
    <el-button type="success" @click="handleAddUser">创建新的用户</el-button>
    <el-button type="warning" @click="handleAddUser">创建新的用户</el-button>


    <!-- 用户列表 -->
    <el-table :data="usersList" style="width: 100%; margin-top: 30px;" border>
      <el-table-column align="center" label="用户名" width="220">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色" width="220">
        <template slot-scope="scope">
          {{ scope.row.role }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="邮箱">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createdAt }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后登录时间">
        <template slot-scope="scope">
          {{ scope.row.lastLoginAt }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
          <el-button type="info" size="small" @click="handleResetPassword(scope)">重置密码</el-button>
          <el-button type="success" size="small" @click="handleViewHistory(scope)">查看历史</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 用户对话框 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'添加用户'">
      <el-form :model="user" label-width="80px" label-position="left">
        <el-form-item label="用户名">
          <el-input v-model="user.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password" placeholder="密码" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="user.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="所属角色">
          <el-select v-model="user.role" placeholder="请选择角色">
            <el-option label="manager" value="manager" />
            <el-option label="Myuser" value="Myuser" />
            <el-option label="visitor" value="visitor" />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { getUsers, addUser, deleteUser, updateUser, resetPassword, viewHistory } from '@/api/User_Login'

const defaultUser = {
  username: '',
  password: '',
  email: '',
  role: '',
}

export default {
  data() {
    return {
      user: Object.assign({}, defaultUser),
      usersList: [
        {
          username: '张三',
          role: '超级管理员',
          email: 'zhangsan@stu.pku.edu.cn',
          createdAt: '2023-10-23',
          lastLoginAt: '2023-10-23'
        },
        {
          username: '李四',
          role: '普通管理员',
          email: 'lisi@stu.pku.edu.cn',
          createdAt: '2021-10-23',
          lastLoginAt: '2023-02-10'
        },
        {
          username: '王五',
          role: '普通用户',
          email: 'wangwu@stu.pku.edu.cn',
          createdAt: '2023-03-01',
          lastLoginAt: '2023-10-15'
        }
      ],
      dialogVisible: false,
      dialogType: 'new'
    }
  },
  created() {
    // 从服务器获取用户列表
    this.getUsers()
  },
  methods: {
    async getUsers() {
      try{
        const res = await getUsers()
        this.usersList = res.data
      }catch(error){
        console.log("拉取用户失败");
      }
    },
    handleAddUser() {
      this.user = Object.assign({}, defaultUser)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.user = deepClone(scope.row)
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认删除该用户吗？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(async() => {
            await deleteUser(row.username)
            this.usersList.splice($index, 1)
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
          })
          .catch(err => { console.error(err) })
    },
    handleResetPassword(scope) {
      this.$confirm('确认重置该用户的密码吗？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(async() => {
            await resetPassword(scope.row.username)
            this.$message({
              type: 'success',
              message: '密码重置成功！'
            })
          })
          .catch(err => { console.error(err) })
    },
    handleViewHistory(scope) {
      viewHistory(scope.row.id)
    },

    async confirmUser() {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        await updateUser(this.user.username, this.user)
        this.getUsers()
      }
      else {
        const { data } = await addUser(this.user)
        this.user.id = data.id
        this.usersList.push(this.user)
      }

      this.dialogVisible = false
      this.$notify({
        title: '成功',
        message: '操作成功！',
        type: 'success'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .users-table {
    margin-top: 30px;
  }

  .el-button + .el-button {
    margin-bottom: 10px;
  }
}
</style>
